package com.welica.wat.impl;

import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import com.welica.wat.config.ZookeeperLockConfig;
import com.welica.wat.stragety.DistributeLockStrategy;

/**
 * @ClassName: ZookeeperLock
 * @Description: Zookeeper实现分布式锁的实现类
 * @author weiyongpeng
 * @date 2024年11月2日 下午4:27:09
 */
@EnableConfigurationProperties(ZookeeperLockConfig.class)
public class ZookeeperLock implements DistributeLockStrategy {

	private static final Logger log = LoggerFactory.getLogger(ZookeeperLock.class);

	private ZookeeperLockConfig zookConfig;
	
	@Autowired
	private CuratorFramework client;
	
	private InterProcessMutex processMutex;
	
	public ZookeeperLock(ZookeeperLockConfig zookConfig) {
		this.zookConfig = zookConfig;
	}

	/**
	 * 描述：zookeeper客户端销毁
	 * 
	 * @Title: destroy
	 * @author weiyongpeng
	 * @date 2024年11月2日 下午6:28:51
	 */
	@PreDestroy
	public void destroy() {
		// 释放zookeeper链接
		if (client != null) {
			try {
				client.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean lock(String lockName, int ttl, boolean isSpin) {
		lockName = zookConfig.getRootPath() + "/" + lockName;
		processMutex = new InterProcessMutex(client, lockName);
		try {
			return processMutex.acquire(ttl, TimeUnit.SECONDS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean unLock(String lockName) {
		try {
			processMutex.release();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean isLocked(String lockName) {
		// TODO Auto-generated method stub
		return false;
	}


}
